package org.example.myleet.p532;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

public class Solution {
    public int findPairs(int[] nums, int k) {
        Map<Integer, Integer> numMapCount = new HashMap<>(nums.length);
        for (int num : nums) {
            int cnt = numMapCount.getOrDefault(num, 0);
            ++cnt;
            numMapCount.put(num, cnt);
        }
        HashSet<Long> numPairSet = new HashSet<>(nums.length);
        int uniquePairCount = 0;
        int target;
        Long numPair;
        for (int num : nums) {
            target = num - k;
            if (numMapCount.containsKey(target)) {
                if (target == num) {
                    int cnt = numMapCount.get(target);
                    if (cnt < 2) {
                        continue;
                    }
                }
                numPair = getNumPair(num, target);
                if (!numPairSet.contains(numPair)) {
                    ++uniquePairCount;
                    numPairSet.add(numPair);
                }
            }
            target = num + k;
            if (numMapCount.containsKey(target)) {
                if (target == num) {
                    int cnt = numMapCount.get(target);
                    if (cnt < 2) {
                        continue;
                    }
                }
                numPair = getNumPair(num, target);
                if (!numPairSet.contains(numPair)) {
                    ++uniquePairCount;
                    numPairSet.add(numPair);
                }
            }
        }
        return uniquePairCount;
    }

    private Long getNumPair(int n1, int n2) {
        if (n1 > n2) {
            return getNumPair(n2, n1);
        }
        return n1 * 100000000L + n2;
    }
}
